import { getDatabaseByKey, objectCopy, pushAutograph, pushTestAstigmatism, pushTestVision, redirectMain, setDatabaseByKey, toLogin, UUID } from "@/common/index/utils/common"
import { lastSignData, lastTestAstigmatismResult, lastTestVsiionResult } from "@/common/index/config/data"
import { choice, showToast } from "./utils/toast"
import { IS_GLASSES } from "./config/Event"
import { astigmatismResultToData, getEstimatePayIssue, visionResultsToInitalData, visionResultToData } from "./utils/format"
import { getLastTestMessage, sendSignImage, sendTestResult } from "@/api/index/api"

class LogicalProcess {
    /**
     * 步骤下标
     */
    #taskStep = 0;
    exec () {
        if (this["task" + this.#taskStep]) {
            setTimeout(() => {
                this["task" + this.#taskStep]()
            }, 300)
        }
    }
    setTaskStep (taskStep) {
        this.#taskStep = taskStep
    }
    getTaskStep () {
        return this.#taskStep
    }
}
/**
 * 体验之前流程
 */
export class BeforeExperiencing extends LogicalProcess {

    /**
     * 戴眼镜测量数据
     */
    wearGlassesTestVsionResult = null
    wearGlassesTestVsionResult_uuid = UUID()


    nakedIndex = 5;
    /**
     * 54321米裸眼测量的数据
     */
    nakedTestVsiionResults = []

    nakedTestVsiionResults_uuid = UUID()


    /**
     * 裸眼测量的数据
     */
    nakedTestVsiionResult = null;

    /**
     * 散光测试数据
     */
    testAstigmatismResult = null
    testAstigmatismResult_uuid = UUID()

    /**
     * 聚光镜测试结果
     */
    condenserLensvisionResult = null
    condenserLensvisionResult_uuid = UUID()


    task0_test_after = false;
    task9_test_after = false;
    task1_test_after = false;
    task2_test_after = false;



    task0 () {
        const display = () => {
            const arr = ["戴镜视力测试", "裸眼视力测试", "散光测试", "聚光镜测试"]
            let dist = 9
            if (!uni.$store.getters[IS_GLASSES]) {
                arr.splice(0, 1)
                dist = 1
            }
            choice("调整前测试项目", arr, true, () => {
                this.setTaskStep(dist)
                this.exec()
            }, () => {
                choice("取消测试", "你要取消测试吗?", true, () => {
                    toLogin()
                }, () => {
                    display()
                })
            }, "开始")
        }
        display()
    }
    /**
     * 测戴眼镜
     */
    task9 () {
        if (!this.task9_test_after) {
            let wearGlassesFlag = uni.$store.getters
            if (wearGlassesFlag) {
                this.task9_test_after = true
                pushTestVision({ testTitle: "戴眼镜", distance: 5, initTestCompanyIndex: 0, uuid: this.wearGlassesTestVsionResult_uuid })
            } else {

                this.setTaskStep(1)
                this.exec()
            }
        } else {
            if (lastTestVsiionResult.uuid == this.wearGlassesTestVsionResult_uuid) {
                this.wearGlassesTestVsionResult = objectCopy(lastTestVsiionResult)
                this.setTaskStep(1)
            } else {
                this.task9_test_after = false
            }
            this.exec()
        }
    }
    getInitTestCompanyIndex () {
        const arr = this.nakedTestVsiionResults
        if (arr.length > 0) {
            return Math.max(Math.min(arr[arr.length - 1].leftCompanyIndex, arr[arr.length - 1].rightCompanyIndex), 0)
        } else
            return 0
    }
    setNakedTestVsiionResult () {
        const arr = this.nakedTestVsiionResults
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].leftCompanyIndex >= 0 || arr[i].rightCompanyIndex >= 0) {
                this.nakedTestVsiionResult = objectCopy(arr[i])
                return
            }
        }
        this.nakedTestVsiionResult = objectCopy(arr[4])
    }
    isTestTesk9 () {
        const arr = this.nakedTestVsiionResults
        const item = arr[arr.length - 1]
        /**
         * 当视力到达1.0的时候就不用继续靠近测量了
         */
        return !(item.leftCompanyIndex >= 10 && item.rightCompanyIndex >= 10)
    }
    /**
     * 测54321
     */
    task1 () {
        if (!this.task1_test_after) {
            this.task1_test_after = true
            pushTestVision({ testTitle: "裸眼", distance: this.nakedIndex, initTestCompanyIndex: this.getInitTestCompanyIndex(), uuid: this.nakedTestVsiionResults_uuid, lockDistance: true })
        } else {
            this.task1_test_after = false
            if (lastTestVsiionResult.uuid != this.nakedTestVsiionResults_uuid) {
                this.exec()
                return
            }

            this.nakedTestVsiionResults.push(objectCopy(lastTestVsiionResult))
            if (--this.nakedIndex < 1) {
                this.setNakedTestVsiionResult()
                this.setTaskStep(2)
            }
            this.exec()
        }
    }
    /**
     * 测散光
     */
    task2 () {
        if (!this.task2_test_after) {
            this.task2_test_after = true
            pushTestAstigmatism({ uuid: this.testAstigmatismResult_uuid })
        } else {
            if (lastTestAstigmatismResult.uuid == this.testAstigmatismResult_uuid) {
                this.testAstigmatismResult = objectCopy(lastTestAstigmatismResult)
                this.setTaskStep(3)
            } else {
                this.task2_test_after = false
            }
            this.exec()
        }
    }
    /**
     * 测聚光镜
     */
    task3 () {
        if (!this.task3_test_after) {
            this.task3_test_after = true
            pushTestVision({ testTitle: "聚光镜", distance: 5, initTestCompanyIndex: 0, uuid: this.condenserLensvisionResult_uuid, lockDistance: true })
        } else {
            if (this.condenserLensvisionResult_uuid == lastTestVsiionResult.uuid) {
                this.condenserLensvisionResult = objectCopy(lastTestVsiionResult)
                this.setTaskStep(4)
            } else {
                this.task3_test_after = false
            }
            this.exec()
        }
    }
    task4 () {
        const payIssue = getEstimatePayIssue(this.nakedTestVsiionResults, this.condenserLensvisionResult)
        setDatabaseByKey(uni.$store.state.nativeData.mobile + "--" + uni.$store.state.nativeData.name, payIssue)
        choice("测试完成", [
            `根据测试结果预算`,
            `建议购买${payIssue}期套餐`], false, () => {
                choice("提交", "是否提交？", true, () => {
                    this.commit()
                }, () => {
                    choice("重新测试", "是否重新测试？", true, () => redirectMain(), () => toLogin())
                })
            }
        )

    }
    // 提交数据
    async commit () {
        const shopId = uni.$store.state.shopId
        const glasses_vision = visionResultToData(this.wearGlassesTestVsionResult)
        const naked_vision = visionResultToData(this.nakedTestVsiionResult)
        const condenser_vision = visionResultToData(this.condenserLensvisionResult)
        const arr = this.nakedTestVsiionResults.map(i => visionResultToData(i))
        const inital_vision = visionResultsToInitalData(arr)
        // 是否测散光
        const is_astigmatism = 1
        const astigmatism_result = astigmatismResultToData(this.testAstigmatismResult)
        const { now_issue, stage } = uni.$store.state.nativeData
        try {
            const res = await sendTestResult({
                shopId,
                glasses_vision,
                naked_vision,
                condenser_vision,
                inital_vision,
                is_astigmatism,
                astigmatism_result,
                issue: now_issue,
                stage
            })
            if (res.statusCode == 200) {
                console.log(2)
                choice("提交成功", "返回登录", false, () => {
                    toLogin()
                })
            } else {
                console.log(3)
                showToast("提交失败", res.data.message, () => {
                    toLogin()
                })
            }
        } catch (e) {
            showToast("提交失败", e.toString(), () => {
                toLogin()
            })
        }
    }
}

/**
 * 体验之后流程
 */
export class AfterExperiencing extends LogicalProcess {
    task1_test_after = false;
    task2_test_after = false;
    task3_test_after = false
    nakedTestVisionResult = null;
    nakedTestVisionResult_uuid = UUID();
    is_astigmatism = 0;
    astigmatismResult = null;
    astigmatismResult_uuid = UUID();
    condenserLensvisionResult = null
    condenserLensvisionResult_uuid = UUID()

    task0 () {
        const display = () => {
            choice("调整后测试", ["裸眼测试", "聚光镜测试", "散光测试"], true, () => {
                this.setTaskStep(1)
                this.exec()
            }, () => {
                choice("取消测试", "你要取消测试吗?", true, () => {
                    toLogin()
                }, () => {
                    display()
                })
            }, "开始")
        }
        display()
    }
    async task1 () {
        if (!this.task1_test_after) {

            //todo 体验后测量的距离
            let lastDistance = await this.loadLastTestMessageTestDistance()
            let nakedIndex = Math.min(uni.$store.state.lastTestVisions[0], uni.$store.state.lastTestVisions[1])
            nakedIndex = Math.max(0, nakedIndex - 1)
            this.task1_test_after = true
            pushTestVision({ testTitle: "裸眼", distance: lastDistance, initTestCompanyIndex: nakedIndex, uuid: this.nakedTestVisionResult_uuid })
        } else {
            if (this.nakedTestVisionResult_uuid == lastTestVsiionResult.uuid) {
                this.nakedTestVisionResult = objectCopy(lastTestVsiionResult)
                this.setTaskStep(2)
            } else {
                this.task1_test_after = false
            }
            this.exec()
        }
    }
    task2 () {
        if (!this.task2_test_after) {
            this.task2_test_after = true
            let condenserIndex = Math.min(uni.$store.state.lastTestVisions[2], uni.$store.state.lastTestVisions[3])
            condenserIndex = Math.max(0, condenserIndex - 1)

            pushTestVision({ testTitle: "聚光镜", distance: 5, initTestCompanyIndex: condenserIndex, uuid: this.condenserLensvisionResult_uuid, lockDistance: true })
        } else {
            if (this.condenserLensvisionResult_uuid == lastTestVsiionResult.uuid) {
                this.condenserLensvisionResult = objectCopy(lastTestVsiionResult)
                this.setTaskStep(3)
            } else {
                this.task2_test_after = false
            }
            this.exec()
        }
    }
    task3 () {
        if (!this.task3_test_after) {
            choice("测试散光", "是否测试散光", true, () => {
                this.task3_test_after = true
                this.is_astigmatism = 1
                pushTestAstigmatism({ uuid: this.astigmatismResult_uuid })
            }, () => {
                this.setTaskStep(4)
                this.exec()
            })

        } else {
            if (this.astigmatismResult_uuid == lastTestAstigmatismResult.uuid) {
                this.astigmatismResult = objectCopy(lastTestAstigmatismResult)
                this.setTaskStep(4)
            } else {
                this.task3_test_after = false
            }
            this.exec()
        }
    }
    task4 () {
        const display = () => {
            choice("提交数据", ["是否提交数据"], true, () => {
                this.commit()
            }, () => {
                choice("重新检测", "是否重新检测？", true, () => redirectMain(), () => toLogin())
            })
        }
        const payIssue = getDatabaseByKey(uni.$store.state.nativeData.mobile + "--" + uni.$store.state.nativeData.name)
        if (payIssue) {
            choice("测试技术", ['根据之前的检测判断', `建议购买${payIssue}期套餐`], false, () => display())
        } else {
            display()
        }


    }
    /**
     * 
     * @returns 获取上一侧测试距离
     */
    async loadLastTestMessageTestDistance () {
        try {
            const { data, statusCode } = await getLastTestMessage()
            if (statusCode == 200) {
                return data.data.naked_vision.left_eye.distance
            } else {
                return 5
            }
        } catch (e) {
            showToast("错误", "获取上次测试结果失败", () => toLogin())
        }
    }
    /**
     * 提交
     */
    async commit () {
        const { issue, stage, shop_id } = uni.$store.state.nativeData
        const naked_vision = visionResultToData(this.nakedTestVisionResult)
        const condenser_vision = visionResultToData(this.condenserLensvisionResult)
        const is_astigmatism = this.is_astigmatism
        const astigmatism_result = this.is_astigmatism == null ? undefined : astigmatismResultToData(this.astigmatismResult)

        const { statusCode, data } = await sendTestResult({
            shopId: shop_id,
            issue,
            stage,
            naked_vision,
            condenser_vision,
            is_astigmatism,
            astigmatism_result
        })
        if (statusCode == 200) {
            choice("提交成功", "返回登录", false, () => toLogin())
        } else {
            showToast("提交错误", data.data.message, () => toLogin())
        }
    }
}
/**
 * 正式测试流程
 */
export class FormalExperiencing extends AfterExperiencing {

    /**
        * 用户签名uuid
        */
    userSignUUID = UUID()
    /**
     * 用户签名
     */
    userSign = undefined
    /**
     * 理疗师签名uuid
     */
    physiotherapistUUID = UUID()
    /**
     * 理疗师签名
     */
    physiotherapist = undefined
    /**
     * 理疗师ID
     */
    physiotherapistId = 0
    /**
     * 纪律签名uuid
     */
    disciplineUUID = UUID()
    /**
     * 纪律签名
     */
    disciplineSign = undefined
    /**
     * 纪律Id
     */
    disciplineSignId = 0

    task4_test_after = false
    task5_test_after = false
    task6_test_after = false
    task0 () {
        /**
         * 第几期测试
         */
        const { now_issue } = uni.$store.state.nativeData

        if (now_issue <= -1) {
            const payIssue = getDatabaseByKey(uni.$store.state.nativeData.mobile + "--" + uni.$store.state.nativeData.name)
            if (payIssue) {
                choice("无法检测", ['您没有购买套餐', "根据之前检测数据判断", `建议购买${payIssue}期套餐`], false, () =>
                    choice("离开", ["准备返回登录"], false, () => toLogin()))
            } else {
                choice("无法测试", ["您没有购买套餐", "准备返回登录"], false, () => toLogin())
            }

            return
        }

        const display = () => {
            choice(`第${now_issue}期测试`, ["裸眼测试", "聚光镜测试", "散光测试"], true, () => {
                this.setTaskStep(1)
                this.exec()
            }, () => {
                choice("取消测试", "你要取消测试吗?", true, () => {
                    toLogin()
                }, () => {
                    display()
                })
            }, "开始")
        }
        display()
    }
    task4 () {
        if (!this.task4_test_after) {
            choice("签名", ["请用户签名"], false, () => {
                this.task4_test_after = true
                pushAutograph({ title: "用户", uuid: this.userSignUUID })
            })
        } else {
            if (this.userSignUUID == lastSignData.uuid) {
                this.userSign = lastSignData.value
                this.setTaskStep(5)

            } else {
                this.task4_test_after = false

            }
            this.exec()
        }
    }
    task5 () {
        if (!this.task5_test_after) {
            choice("签名", ["请理疗师签名"], false, () => {
                this.task5_test_after = true
                pushAutograph({ title: "理疗师", uuid: this.physiotherapistUUID, selectTrainer: true })
            })
        } else {
            if (this.physiotherapistUUID == lastSignData.uuid) {
                this.physiotherapist = lastSignData.value
                this.physiotherapistId = lastSignData.signid
                this.setTaskStep(6)
            } else {
                this.task5_test_after = false
            }
            this.exec()
        }
    }
    task6 () {
        if (!this.task6_test_after) {
            choice("签名", ["请纪律签名"], false, () => {
                this.task6_test_after = true
                pushAutograph({ title: "纪律", uuid: this.disciplineUUID, isRectangle: true, selectTrainer: true })
            })
        } else {
            if (this.disciplineUUID == lastSignData.uuid) {
                this.disciplineSign = lastSignData.value
                this.disciplineSignId = lastSignData.signid
                this.setTaskStep(7)
            } else {
                this.task6_test_after = false
            }
            this.exec()
        }
    }
    task7 () {
        setTimeout(() => {
            choice("测试结束", ["是否提交测试数据？"], true, () => {
                this.commit()
            }, () => {
                choice("重新测试", "是否重新测试", true, () => redirectMain(), () => toLogin())
            }, "提交")
        }, 300)
    }
    async commit () {
        const { now_issue, stage, shop_id } = uni.$store.state.nativeData
        const naked_vision = visionResultToData(this.nakedTestVisionResult)
        const condenser_vision = visionResultToData(this.condenserLensvisionResult)
        const is_astigmatism = this.is_astigmatism
        const astigmatism_result = this.is_astigmatism == null ? null : astigmatismResultToData(this.astigmatismResult)
        const signature = await sendSignImage({ filePath: this.userSign })
        const trainer_signature = await sendSignImage({ filePath: this.physiotherapist })
        const morale_signature = await sendSignImage({ filePath: this.disciplineSign })
        const trainer_id = this.physiotherapistId
        const morale_id = this.disciplineSignId
        const { statusCode, data } = await sendTestResult({
            shopId: shop_id,
            issue: now_issue,
            stage,
            naked_vision,
            condenser_vision,
            is_astigmatism,
            astigmatism_result,
            signature,
            trainer_signature,
            morale_signature,
            trainer_id,
            morale_id
        })
        if (statusCode == 200) {
            choice("提交成功", "返回登录", false, () => toLogin())
        } else {
            showToast("提交错误", data.data.message, () => toLogin())
        }
    }
}
